package cq.zhcqk;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.dou361.dialogui.DialogUIUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.Map;

import cq.zhcqk.db.TabDb;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.ImeiHelper;
import cq.zhcqk.util.PhoneHelper;
import cq.zhcqk.util.SharedPreferencesHelper;
import cq.zhcqk.util.SpUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.update.UpdateXmlUtil;


public class MainActivity extends FragmentActivity implements OnTabChangeListener{

    private FragmentTabHost tabHost;
    protected AsyncHttpClient httpClient;
    protected SharedPreferences mSharedPreferences;
    protected Context context;

    private boolean is_closed = true;
    private long mExitTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        Uri uridata = this.getIntent().getData();
//        String mydata = uridata.getQueryParameter("data");
        tabHost=(FragmentTabHost)super.findViewById(android.R.id.tabhost);
        tabHost.setup(this,super.getSupportFragmentManager()
                ,R.id.contentLayout);
        tabHost.getTabWidget().setDividerDrawable(null);
        tabHost.setOnTabChangedListener(this);
        initTab();
        context = this;
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        mSharedPreferences = SpUtil.getSpBykey(context, SpUtil.TOKEN);
        autoLogin();
        checkUpdate();
        if(SharedPreferencesHelper.isFirst(context)){
            record();
        }
    }

    /**
     * 检查更新
     */
    private void checkUpdate(){
        UpdateXmlUtil updateXmlUtil = new UpdateXmlUtil(context);
        updateXmlUtil.Update();
    }

    private void initTab(){
        String tabs[]= TabDb.getTabsTxt();
        for(int i=0;i<tabs.length;i++){
            TabSpec tabSpec=tabHost.newTabSpec(tabs[i]).setIndicator(getTabView(i));
            tabHost.addTab(tabSpec,TabDb.getFragments()[i],null);
            tabHost.setTag(i);
        }
    }

    private View getTabView(int idx){
        View view=LayoutInflater.from(this).inflate(R.layout.footer_tabs,null);
        ((TextView)view.findViewById(R.id.tvTab)).setText(TabDb.getTabsTxt()[idx]);
        if(idx==0){
            ((TextView)view.findViewById(R.id.tvTab)).setTextColor(Color.RED);
            ((ImageView)view.findViewById(R.id.ivImg)).setImageResource(TabDb.getTabsImgLight()[idx]);
        }else{
            ((ImageView)view.findViewById(R.id.ivImg)).setImageResource(TabDb.getTabsImg()[idx]);
        }
        return view;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onTabChanged(String tabId) {
        // TODO Auto-generated method stub
        updateTab();

    }
    private void updateTab(){
        TabWidget tabw=tabHost.getTabWidget();
        for(int i=0;i<tabw.getChildCount();i++){
            View view=tabw.getChildAt(i);
            ImageView iv=(ImageView)view.findViewById(R.id.ivImg);
            if(i==tabHost.getCurrentTab()){
                ((TextView)view.findViewById(R.id.tvTab)).setTextColor(Color.RED);
                iv.setImageResource(TabDb.getTabsImgLight()[i]);
            }else{
                ((TextView)view.findViewById(R.id.tvTab)).setTextColor(getResources().getColor(R.color.foot_txt_gray));
                iv.setImageResource(TabDb.getTabsImg()[i]);
            }

        }
    }

    private void autoLogin(){
        String ph = mSharedPreferences.getString("phone",null);
        String pwd =  mSharedPreferences.getString("password",null);
        if(ph!=null&&pwd!=null&&!"".equals(ph)&&!"".equals(pwd)){
            login(ph,pwd);
        }
    }

    private void login(final String ph, final String pwd){
        RequestParams params = new RequestParams();
        params.add("phone",ph);
        params.add("password",pwd);
        httpClient.post(Common.URL+Common.LOGIN,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
//                    Toast.makeText(context,"登录失败，请检查用户名或密码",Toast.LENGTH_SHORT).show();
                }else{
                    Map<String, Object> data = (Map<String, Object>) map.get("data");
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putString("id",data.get("id")+"");
                    editor.putString("idcard",data.get("idcard")+"");
                    editor.putString("loginname",data.get("loginname")+"");
                    editor.putString("mobilephone",data.get("mobilephone")+"");
                    editor.putString("name",data.get("name")+"");
                    editor.putString("picaddress",data.get("picaddress")+"");
                    editor.putString("token",data.get("token")+"");
                    editor.putString("type",data.get("type")+"");
                    editor.putString("var01",data.get("var01")+"");
                    editor.putString("phone",ph);
                    editor.putString("password",pwd);
                    editor.commit();
                    AsyncHttpClientUtils.setHeader(data.get("token")+"");
                    app.isLogin = true;
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                app.isLogin = false;
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                app.isLogin = false;
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    /**
     * 统计
     */
    private void record(){
        RequestParams params = new RequestParams();
        params.add("imei", ImeiHelper.getImei(context));
        params.add("model",PhoneHelper.getSystemModel());
        params.add("version", PhoneHelper.getLocal(context)+"");
        httpClient.post(Common.URL+Common.RECORD,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("安装调用onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (is_closed) {
                // 判断两次点击的时间间隔（默认设置为2秒）
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();

                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                    System.exit(0);
                    super.onBackPressed();
                }
            } else {
//                resideMenu.closeMenu();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (Util.isOnMainThread()) {
//            Glide.with(context).pauseRequests();
//        }
    }
}
